package org.fei.demo.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ThreadPoolTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        List<String> datas = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            datas.add("数据-"+i);
        }
        int threadSize = 3;
        ExecutorService executorService = Executors.newFixedThreadPool(threadSize);
        ExecutorCompletionService<Integer> ecs = new ExecutorCompletionService<>(executorService);
        ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>(datas);
        for (int i = 0; i < threadSize; i++) {
            ecs.submit(()->{
                int count = 0;
                String data = queue.poll();
                while (data != null){
                    System.out.println(Thread.currentThread().getName()+": "+data);
                    count++;
                    Thread.sleep(500);
                    data = queue.poll();
                }
                return count;
            });
        }
        int resultCount = 0;
        for (int i = 0; i < threadSize; i++) {
            int count = ecs.take().get();
            System.out.println("线程 "+i+" 处理数 "+count);
            resultCount = resultCount + count;
        }
        System.out.println("处理总数："+resultCount);
    }
}
